<?php defined('SYSPATH') OR die('No direct access allowed.');

require_once "gapi/src/apiClient.php";
require_once "gapi/src/contrib/apiLatitudeService.php";

class Redbus_Controller extends Controller {

    public function getDestinations($source='')
	{
	  $redbus = new Redbus_Model();
	  echo json_encode($redbus->getDestinations($source));
	}

	public function getAvailableBuses($source, $destination) {
	  $redbus = new Redbus_Model();
	  echo json_encode($redbus->getBusesAvailableToday($source, $destination));	  
	}	
	
	public function getAvailableBuses1($source, $sourcename, $destination, $destinationname, $doj) {
	   $url = 'http://www.redbus.in/booking/SearchResultsJSON.aspx?';
	   $url = $url . "fromcityid=".$source;
	   $url = $url . "&fromcityname=".$sourcename;
	   $url = $url . "&tocityid=".$destination;
	   $url = $url . "&tocityname=".$destinationname;
	   $url = $url . "&doj=".$doj;	   
	   $curl = curl_init($url);
	   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	   $data = curl_exec($curl);
	   $data = substr($data, 17);
	   $data = substr($data, 0, strlen($data)-1);
	   
	   //////////////JSON Formatting...
	   $objs = json_decode($data);
	   $detailsNeeded = array();
	   foreach ($objs as $obj) {
	     $bus = new stdClass();
	     $bus->travels = $obj->travelsName;
	     $bus->bps = array();
	     foreach($obj->BPInformationList as $Bps) {
	       $bpDetails = new stdClass();
	       $bpDetails->bpTime = $Bps->bpTime;
	       $bpDetails->location = $Bps->bpLocation;
	       array_push($bus->bps, $bpDetails);
	     }
	     array_push($detailsNeeded, $bus);	     
	   }
	   
	   echo(json_encode($detailsNeeded));
	   curl_close($curl);
	}

} 
